package cn.git.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.serializer.RedisSerializationContext;

import java.time.Duration;

/**
 * @description: redis配置类
 * @program: bank-credit-sy
 * @author: lixuchun
 * @create: 2024-09-23
 */
@Slf4j
@Configuration
@EnableCaching
public class RedisCacheConfig extends CachingConfigurerSupport {

    /**
     * redis序列化器
     */
    private static final FastJson2JsonRedisSerializer REDIS_SERIALIZER = new FastJson2JsonRedisSerializer();

    /**
     * 自定义key生成器， 拼接名称class名称 + 方法名称 + 参数列表
     *
     * @return
     */
    @Bean(name = "customKeyGenerator")
    public KeyGenerator customKeyGenerator(){
        // 三个参数分别为 当前类，方法，参数列表
        return (object, method, params) -> {
            // 拼接名称class名称 + 方法名称 + 参数列表
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append(object.getClass().getName());
            stringBuilder.append(method.getName());
            // 拼接参数信息
            for(Object param: params){
                stringBuilder.append(param == null ? "null" : param.toString());
            }
            return stringBuilder.toString();
        };
    }

    /**
     * 配置缓存管理器
     *
     * @param connectionFactory
     * @return
     */
    @Bean
    public RedisCacheManager cacheManager(RedisConnectionFactory connectionFactory) {
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
                // 设置缓存的过期时间，单位秒
                .entryTtl(Duration.ofSeconds(60))
                // 设置key的序列化方式
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(REDIS_SERIALIZER))
                // 设置value的序列化方式
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(REDIS_SERIALIZER))
                // 不缓存null值
                .disableCachingNullValues();

        // 配置缓存管理器
        return RedisCacheManager.builder(connectionFactory)
                .cacheDefaults(config)
                .transactionAware()
                .build();
    }

}
